//
//  CYStatusViewModel.swift
//  WeiBo
//
//  Created by Mr_J on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class CYStatusViewModel: NSObject {

    var status: CYStatus? {
        didSet {
            print("status didSet")
        }
    }
    
    var verifiedImage: UIImage?
    
    var membershipImage: UIImage?
    
    var repostsCountStr: String?
    // 评论数量
    var commentsCountStr: String?
    // 点赞数量
    var attitudesCountStr: String?
    
    var retweetedText: String?
    
    var sourceText: String?
    
    
    init(status: CYStatus) {
        super.init()
        self.status = status
        
        let verifiedType = status.user?.verified ?? -1
        
        switch verifiedType {
            
        case 1:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
            
        default:
            verifiedImage = nil
        }
        
        if let mbrank = status.user?.mbrank where mbrank > 0 {
            membershipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
        repostsCountStr = stringWithCount(status.reposta_count, defaultString: "转发")
        commentsCountStr = stringWithCount(status.comments_count, defaultString: "评论")
        attitudesCountStr = stringWithCount(status.attitudes_count, defaultString: "赞")
        
        
        //转发微博内容
        
        if let screenName = status.retweeted_status?.user?.screen_name, text = status.retweeted_status?.text {
            retweetedText = "@\(screenName):\(text)"
        }else {
            retweetedText = "该微博已经被删除"
        }
        
        dealSourceText(status.source)
        
    }
    
    private func stringWithCount(count: Int, defaultString: String) -> String {
        
        if count < 10000 {
            if count == 0 {
                return defaultString
            }else {
                return "\(count)"
            }
        }else {
            let result = CGFloat(count / 1000)/10
            let resultStr = "\(result)万"
            
            if resultStr.containsString(".0") {
                return resultStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return resultStr
        }
        
        
    }
    func dealSourceText(source: String?) {
        
        
        guard let s = source else {
            return
        }
        if let startIndex = s.rangeOfString("\">")?.endIndex {
            if let endIndex = s.rangeOfString("</")?.startIndex {
                sourceText = "来自 \(s.substringWithRange(startIndex..<endIndex))"

        }
    }
    }
    
    
    

}